import {Loading} from 'element-ui'
// import Vue from "vue";
// 检查值是否存在
export function examineValue(value) {
  let strValue = JSON.stringify(value)
  if (
    strValue &&
    strValue !== '' &&
    strValue !== 'false' &&
    strValue !== 'null' &&
    strValue !== 'undefined' &&
    strValue !== '{}' &&
    strValue !== '[]'
  ) {
    return true
  }
  return false
}

//获取url中"?"符后的字串
export function getRequest() {
  let url = location.href //获取url中"?"符后的字串
  let theRequest = {}
  if (url.indexOf('?') != -1) {
    let str = url.substr(url.indexOf('?') + 1)
    let strs = str.split('&')
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }
  return theRequest
}

/*
 * js小数加法
 */
export function accAdd(arg1, arg2) {
  if (isNaN(arg1)) {
    arg1 = 0
  }
  if (isNaN(arg2)) {
    arg2 = 0
  }
  arg1 = Number(arg1)
  arg2 = Number(arg2)
  let r1, r2, m, c
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  c = Math.abs(r1 - r2)
  m = Math.pow(10, Math.max(r1, r2))
  if (c > 0) {
    let cm = Math.pow(10, c)
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace('.', ''))
      arg2 = Number(arg2.toString().replace('.', '')) * cm
    } else {
      arg1 = Number(arg1.toString().replace('.', '')) * cm
      arg2 = Number(arg2.toString().replace('.', ''))
    }
  } else {
    arg1 = Number(arg1.toString().replace('.', ''))
    arg2 = Number(arg2.toString().replace('.', ''))
  }
  return (arg1 - arg2) / m
}

// 小数位数
export function decimalsDigit(str, num) {
  let number
  if (typeof str !== 'number') {
    let parseStr = parseFloat(str)
    if (parseStr.toString() === 'NaN') {
      number = str
    } else {
      number = parseStr.toFixed(num)
    }
  } else {
    number = str.toFixed(num)
  }
  return number
}

//显示loading 实例
export function loading() {
  this.show = function () {
    this.loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0)',
    })
  }
  this.close = function () {
    this.loading.close()
  }
  this.show()
}

// 转换
export function conver(limit) {
  let size = ''
  if (limit < 0.1 * 1024) {
    //如果小于0.1KB转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 0.1 * 1024 * 1024) {
    //如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {
    //如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  let sizestr = size + ''
  let len = sizestr.indexOf('.')
  let dec = sizestr.substr(len + 1, 2)
  if (dec == '00') {
    //当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
  }
  return sizestr
}

// 小数乘法
export function accMul(arg1, arg2) {
  let m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString()
  if (s1.split('.')[1] && s1.split('.')[1].length) {
    try {
      m += s1.split('.')[1].length
    } catch (e) {
      console.log(e)
    }
  }
  try {
    m += s2.split('.')[1].length
  } catch (e) {
    console.log(e)
  }
  return (
    (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
    Math.pow(10, m)
  )
}

// 时间格式化
const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 时间格式处理函数
/*
 * number:时间锉
 * format(string):时间格式 'Y-M-D h:m:s'
 * */
export function formatTime(number, format) {
  let formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  let returnArr = []
  let date
  if (Number(number) != number) {
    date = new Date(number.replace(/-/g, '/'))
  } else {
    date = new Date(number)
  }

  returnArr.push(date.getFullYear())
  returnArr.push(formatNumber(date.getMonth() + 1))
  returnArr.push(formatNumber(date.getDate()))

  returnArr.push(formatNumber(date.getHours()))
  returnArr.push(formatNumber(date.getMinutes()))
  returnArr.push(formatNumber(date.getSeconds()))
  for (let i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format
}

// 判断缩放
export function zoomRatio() {
  let ratio = 0
  let screen = window.screen
  let ua = navigator.userAgent.toLowerCase()

  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth
  }

  if (ratio) {
    ratio = Math.round(ratio * 100)
  }
  if (browsers() === 'Chrome' || browsers() === 'Edge') {
    return ratio
  } else {
    return 100
  }
}

// 浏览器判断
export function browsers() {
  let userAgent = navigator.userAgent //取得浏览器的userAgent字符串
  if (userAgent.indexOf('Chrome') > -1) {
    if (userAgent.indexOf('Edge') > -1) {
      return 'Edge'
    } else {
      return 'Chrome'
    }
  } else if (userAgent.indexOf('Firefox') > -1) {
    return 'Firefox'
  }
}

// 防抖
export function debounce(callback, wait = 1000) {
  var timeId = null
  // 闭包的应用
  return function () {
    var self = this
    var args = arguments
    // 清除可能存在的timeId
    if (timeId !== null) {
      clearTimeout(timeId)
    }
    timeId = setTimeout(() => {
      // 必须使用apply或者call,将回调函数的this指向Vue
      callback.apply(self, args)
    }, wait)
  }
}

// 订阅发布机制

export const listeners = {}
export const events = []

export const on = (event, callback) => {
  // console.log('on', event)
  for (let i = 0; i < events.length; i++) {
    // 判断如果
    if (events[i].event === event) {
      callback(events[i].data)
      events.splice(i, 1)
    }
  }
  listeners[event] = callback
}
export const emit = (event, data) => {
  const callback = listeners[event]
  if (callback) {
    callback(data)
  } else {
    events.push({event, data})
  }
}

export function changeData(s) {
  //如果存在ArrayBuffer对象(es6) 最好采用该对象
  if (typeof ArrayBuffer !== 'undefined') {

    //1、创建一个字节长度为s.length的内存区域
    let buf = new ArrayBuffer(s.length);

    //2、创建一个指向buf的Unit8视图，开始于字节0，直到缓冲区的末尾
    let view = new Uint8Array(buf);

    //3、返回指定位置的字符的Unicode编码
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;

  } else {
    let buf = new Array(s.length);
    for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
}

// url拼接
export function disposeParam(url, param) {
  if (examineValue(param)) {
    for (let key in param) {
      url = url.replace('{' + key + '}', param[key])
    }
  }
  // console.log(url)
  return url
}

const format1 = (time) => {
  let ymd = ''
  let mouth =
    time.getMonth() + 1 >= 10
      ? time.getMonth() + 1
      : '0' + (time.getMonth() + 1)
  let day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()
  ymd += mouth + '-' // 获取月份。
  ymd += day // 获取日。
  return ymd // 返回日期。
}
const format = (time) => {
  let ymd = ''
  let mouth =
    time.getMonth() + 1 >= 10
      ? time.getMonth() + 1
      : '0' + (time.getMonth() + 1)
  let day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()
  ymd += time.getFullYear() + '-' // 获取年份。
  ymd += mouth + '-' // 获取月份。
  ymd += day // 获取日。
  return ymd // 返回日期。
}
// 已知开始时间和结束时间 计算出中间的所有日期
export const getAllDate = (start, end) => {
  let dateArr = []
  let startArr = start.split('-')
  let endArr = end.split('-')
  let db = new Date()
  db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
  let de = new Date()
  de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
  let unixDb = db.getTime()
  let unixDe = de.getTime()
  let stamp
  const oneDay = 24 * 60 * 60 * 1000
  for (stamp = unixDb; stamp <= unixDe;) {
    dateArr.push(format1(new Date(parseInt(stamp))))
    stamp = stamp + oneDay
  }
  return dateArr
}

// 最近七天

export const getWeekDate = () => {
  let myDate = new Date()
  // 获取前一周时间
  const oneDay = 24 * 60 * 60 * 1000
  let oneweekdate = new Date(myDate - 7 * oneDay)
  let lastWeek = []
  lastWeek.push(format(oneweekdate))
  lastWeek.push(format(myDate))
  return lastWeek
}

//最近一个月:
export const getMonthDate = () => {
  let nowDate = new Date()
  let nowDateChange = new Date()
  let lastMonth = []
  // 获取前一月时间
  nowDateChange.setMonth(nowDateChange.getMonth() - 1)
  lastMonth.push(format(nowDateChange))
  lastMonth.push(format(nowDate))
  return lastMonth
}

//最近三个月
export const getThreeMonthDate = () => {
  let nowDate = new Date()
  let nowDateChange = new Date()
  let threeMonth = []
  // 获取前三月时间
  nowDateChange.setMonth(nowDateChange.getMonth() - 3)
  threeMonth.push(format(nowDateChange))
  threeMonth.push(format(nowDate))
  return threeMonth
}
//最近一年
export const getYearDate = () => {
  let nowDate = new Date()
  let nowDateChange = new Date()
  let lastYear = []
  // 获取前一年时间
  nowDateChange.setFullYear(nowDateChange.getFullYear() - 1)
  lastYear.push(format(nowDateChange))
  lastYear.push(format(nowDate))
  return lastYear
}

// 拼接 接口? 后面的参数
export function encodeSearchParams(obj) {
  const params = []
  Object.keys(obj).forEach((key) => {
    let value = obj[key]
    // 如果值为undefined置空
    if (typeof value === 'undefined') {
      value = ''
    }
    //使用encodeURIComponent进行编码
    if (Array.isArray(obj[key])) {
      //类型为数组的时候
      value.forEach((item) => {
        params.push([key, encodeURIComponent(item)].join('='))
      })
    } else if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
      //类型为对象的时候
      Object.keys(obj[key]).forEach((item) => {
        params.push([key, encodeURIComponent(obj[key][item])].join('='))
      })
    } else {
      params.push([key, encodeURIComponent(value)].join('='))
    }
  })
  return '?' + params.join('&')
}

// 获取文件名称
export function getFlieName(response) {
  if (response.headers['content-disposition']) {
    const content = response.headers['content-disposition']
    return content && content.split(';')[1].split('filename=')[1]
  }
}

// 获取文件大小
export function bytesToSize(bytes) {
  if (bytes === 0) return '0 B'
  var k = 1000, // or 1024
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

// cookie字符串转对象
export function cookieToJson(str, type) {
  // cookie字符串转对象
  let cookieArr = str.split(";");
  let cookieArray = [];
  let out_obj = {}
  cookieArr.forEach((i) => {
    let obj = {}
    let arr = i.split("=");
    obj.name = arr[0].trim();
    obj.value = arr[1].trim();
    obj.domain = "jshopx.jd.com";
    obj.httpOnly = false;
    obj.secure = false;
    cookieArray.push(obj);
    if (type == obj.name) {
      out_obj = obj
    }
  });
  return out_obj != {} ? out_obj : cookieArray;
}

// 中文排序
const getChartType = (char) => {
  // 数字可按照排序的要）求进行自定义，我这边产品的要求是
  // 数字（0->9）->大写字母（A->Z->小写字母（a->z）->中文拼音（a->z）
  if (/^[\u4e00-\u9fa5]$/.test(char)) {
    return ['zh', 300]
  }
  if (/^[a-zA-Z]$/.test(char)) {
    return ['en', 200]
  }
  if (/^[0-9]$/.test(char)) {
    return ['number', 100]
  }
  return ['others', 999]
}
// 排序比较字符
export function sortDevChinese(str1, str2) {
  let a = str1
  let b = str2
  let res = 0
  for (let i = 0; ; i++) {
    if (!a[i] || !b[i]) {
      res = a.length - b.length
      break
    }
    const char1 = a[i]
    const char1Type = getChartType(char1)
    const char2 = b[i]
    const char2Type = getChartType(char2)
    // 类型相同的逐个比较字符
    if (char1Type[0] === char2Type[0]) {
      if (char1 === char2) {
        continue
      } else {
        if (char1Type[0] === 'zh') {
          res = char1.localeCompare(char2)
        } else if (char1Type[0] === 'en') {
          res = char1.charCodeAt(0) - char2.charCodeAt(0)
        } else {
          res = char1 - char2
        }
        break
      }
    } else {
      // 类型不同的，直接用返回的数字相减
      res = char1Type[1] - char2Type[1]
      break
    }
  }
  return res
}

// 获取表单
export function getFormKey(formList, key, type = 'key') {
  let findFrom = formList.find((item) => {
    return item[type] === key
  })
  return findFrom.value
}

// 设置表单的值
export function setFormKey(formList, key, value, type = 'key') {
  let findFrom = formList.find((item) => {
    return item[type] === key
  })
  if (findFrom) {
    findFrom.value = value
  }
}

//生成唯一ID
export function guid() {
  return Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36);
}

export function timestampTime(timestamp) {
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}
